﻿using System.Collections;
using System.Collections.Generic;
using TableProto;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
public class MatrixWindow : SingletonBaseWindow<MatrixWindow>
{
    //内容  行和列数   有标题  + 1
    public int colCount = 3;
    public int rowCount = 3;

    //随机显示矩阵结果的数量
    int randomShowNum = 3;
    int dragTotalNum;
    /// <summary>
    /// 每五关切换一个难度
    /// </summary>
    int ndNum = 5;

    #region ui property
    public Button _Btn_Return { get; set; }
    public Transform _matrix_item { get; set; }

    public Transform _matrixGrid { get; set; }

    public Transform _DragItems { get; set; }

    public Transform _MatrixSpace { get; set; }

    public Transform _enableEvent { get; set; }
    #endregion

    Image titleTrans;
    List<Transform> rowTitleList;
    List<Transform> columnTitleList;
    public List<MatrixSpaceItem> spaceItemList;
    List<MatrixDragItem> dragItemList;
    //CanvasGroup dragCanvasGroup;

    /// <summary>
    /// 只在游戏初始化生成一次
    /// </summary>
    public void GenerateItem()
    {
        //有行和列
        rowTitleList = new List<Transform>();
        columnTitleList = new List<Transform>();
        spaceItemList = new List<MatrixSpaceItem>();
        dragItemList = new List<MatrixDragItem>();
        //从左往右  生成
        for (int i = 0; i < rowCount + 1; i++)
        {
            for (int j = 0; j < colCount + 1; j++)
            {
                //0 - 15  ; 1- 16
                int index = j + i * (colCount + 1) + 1;

                GameObject go = GameObject.Instantiate(_matrix_item.gameObject, _matrixGrid);
                go.SetActive(true);
                if (i == 0 && j == 0)
                {
                    titleTrans = go.transform.GetChild(0).GetChild(0).GetComponent<Image>();
                    go.transform.GetChild(0).GetComponent<Image>().color = new Color(1, 1, 1, 0);
                }//||index == 1 ()
                else if (j == 0)//index <= colNum + 1
                {
                    //行
                    rowTitleList.Add(go.transform.GetChild(0).transform);
                    go.transform.GetChild(0).GetComponent<BoxCollider2D>().enabled = false;
                }
                else if (i == 0)
                {
                    //列
                    columnTitleList.Add(go.transform.GetChild(0).transform);
                    go.transform.GetChild(0).GetComponent<BoxCollider2D>().enabled = false;
                }
                else
                {
                    //结果格
                    spaceItemList.Add(go.transform.GetChild(0).gameObject.AddComponent<MatrixSpaceItem>());
                }
            }
        }
        #region  ...
        /*
        for (int i = 1; i <= 16; i++)
        {
            GameObject go = GameObject.Instantiate(_matrix_item.gameObject, _matrixGrid);
            go.SetActive(true);
            if (i == 1)
            { }
            else if (i ==2 || i ==3 || i== 4)
            {
                rowTitleList.Add(go.transform);
                go.transform.GetChild(0).GetComponent<BoxCollider2D>().enabled = false;
            }
            else if (i == 5 || i == 9 || i == 13)
            {
                columnTitleList.Add(go.transform);
                go.transform.GetChild(0).GetComponent<BoxCollider2D>().enabled = false;
            }
            else
            {
                spaceItemList.Add(go.AddComponent<MatrixSpaceItem>());
            }
        }*/
        #endregion       
    }

    public int curLevel;
    public MatrixType curMatrixType;
    //等级总数
    public int curLelCount;
    public void StartGame(MatrixType type,int lelCount, int level = 1)
    {        
        //Debug.Log("StartGame === "+ curLelCount + " , lelCount== "+ lelCount);
        curDragCount = 0;
        curLevel = level;
        curMatrixType = type;
        curLelCount = lelCount;        
        _enableEvent.SetActive(curLevel == 1);
        if(curLevel == 1)
            MedalWindow.Instance.ShowXunzhang(0, false, MedalWindow.EXZCountEnum.Five);
        if (rowTitleList == null || columnTitleList == null || spaceItemList == null || dragItemList == null)
        {
            //第一次进入 没有生成
            GenerateItem();
        }
        else
            OnClear();

        if (dragItemList == null || dragItemList.Count == 0)
        {
            for (int i = 0; i < _DragItems.childCount; i++)
            {
                MatrixDragItem mgi = _DragItems.GetChild(i).GetComponent<MatrixDragItem>();
                if (mgi == null)
                    mgi = _DragItems.GetChild(i).gameObject.AddComponent<MatrixDragItem>();
                dragItemList.Add(mgi);
            }
        }

        var ml = MatrixModel.Instance.GetLevelByLelType(curMatrixType, curLevel);
        //Debug.Log(ml.ToString() + "  === ml ");
        if (ml == null) return;
        if (!titleTrans.gameObject.activeSelf)
        {
            //titleTrans.sprite = CommonUtility.GetSprite(MatrixModel.Instance.GetAtlas(curMatrixType), ml.titleRes);
            titleTrans.sprite = ResourceManager.Instance.GetResource(MatrixModel.Instance.GetAtlas(curMatrixType) + ml.titleRes, typeof(Sprite), enResourceType.Prefab).m_content as Sprite;
            titleTrans.SetNativeSize();
            titleTrans.gameObject.SetActive(true);
        }

        System.Action action = () =>
        {
            this.AddTimerEx(0.2f, () =>
            {
                RefreshUI(ml);

                if (curLevel == 1)
                {
                    WindowManager.Instance.OpenWindow(WinNames.EnglishLediAnimationPanel);
                    //EnglishLediAnimationWindow.Instance.PlayLediTalkAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomLeft, this.GetAudioNameEx(StudyAudioName.t_32009), () =>
                      EnglishLediAnimationWindow.Instance.PlayLediTalkAnimation(EnglishLediAnimationWindow.ELediFadeInType.BottomLeft, MatrixResType.audioPath + MatrixModel.Instance.GetAudio(curMatrixType),()=>
                    {
                        //开启事件
                        _enableEvent.SetActive(false);
                    });
                }
            });
        };
        if (curLevel % ndNum == 1)
        {
            _MatrixSpace.localPosition = new Vector3(-706f, 0, 0);
            _MatrixSpace.DOLocalMoveX(-271f, 0.5f).SetEase(Ease.Linear).OnComplete(() =>
            {
                AudioManager.Instance.PlaySound(MatrixResType.audioPath + "603060105");
                action();
            });
        }
        else
        {
            AudioManager.Instance.PlaySound(MatrixResType.audioPath + "603060105");
            action();
        }
    }
    
    void RefreshUI(MatrixLevel ml)
    {
        //确定矩阵标题   行标题(是否随机)   列标题(是否随机)
        //取 Type  1 - 15的数据   
        //ToDo 获取数据  ，随机三个放好位置， 随机六个放入右侧 
        
        //设计标题
        string[] rowTitiles = MatrixModel.Instance.DesignMatrixTitle(ml.rowTitles, ml.rIsRandom, rowCount);
        string[] colTitiles = MatrixModel.Instance.DesignMatrixTitle(ml.columnTitles, ml.cIsRandom, colCount);

        SetTitleItem(rowTitiles, rowTitleList);
        SetTitleItem(colTitiles, columnTitleList);

        //随机显示格子 (存储的下标 0 - 9)
        int[] _defaultMatrixs = MatrixModel.Instance.RandomTitles(randomShowNum, rowCount * colCount);

        //设置Item和关联关系  格子数据
        SetItem((int)ml.id, rowTitiles, colTitiles, _defaultMatrixs);
    }

    /// <summary>
    /// 设置格子数据
    /// </summary>
    /// <param name="lelId"></param>
    /// <param name="rowTitiles"></param>
    /// <param name="colTitiles"></param>
    /// <param name="_defaultMatrixs"></param>
    void SetItem(int lelId, string[] rowTitiles, string[] colTitiles, int[] _defaultMatrixs)
    {
        int dragIndex = 0;
        int[] _dragItemArray = MatrixModel.Instance.RandomTitles(dragTotalNum, dragTotalNum);
        int animIndex = 1;
        for (int i = 0; i < rowCount; i++)
        {
            for (int j = 0; j < colCount; j++)
            {
                //rowTitiles[i],colTitiles[j];
                var model = MatrixModel.Instance.GetResultByLelIdRowCol(lelId, rowTitiles[i], colTitiles[j]);
                if (model == null)
                {
                    Debug.LogError("  表数据出错 ！！！！  ");
                }
                else
                {
                    string resultName = model.resultname;
                    //Debug.Log(resultName + "  ==== resultName  , i == " + rowTitiles[i] + "  , j== " + colTitiles[j] );
                    // 0 - 8
                    int index = j + i * colCount;
                    MatrixSpaceItem msi = spaceItemList[index];
                    msi.index = index;
                    msi.resultName = resultName;
                    if (IsDefaultMatrixs(_defaultMatrixs, index))
                    {
                        animIndex++;
                        this.AddTimerEx(animIndex * 0.08f, () =>
                        {
                            msi.SetDefaultSpace(curMatrixType, resultName, model.resRotation);
                        });
                    }
                    else
                    {
                        //需要拼的功能格子
                        dragItemList[_dragItemArray[dragIndex]].SetItem(curMatrixType, resultName, index, i, j, model.resRotation);
                        dragIndex++;

                        msi.SetItemBg(true);
                    }
                }
            }
        }
    }
    /// <summary>
    /// 设置标题数据 （可清除）
    /// </summary>
    /// <param name="titles"></param>
    /// <param name="list"></param>
    /// <param name="isClear">是否清除标题内容</param>
    void SetTitleItem(string[] titles, List<Transform> list, bool isClear = false)
    {
        int animIndex = 1;
        string atlas = MatrixResType.NumAtlas;
        if (!isClear)
            atlas = MatrixModel.Instance.GetAtlas(curMatrixType);
        for (int i = 0; i < list.Count; i++)
        {
            if (!isClear)
            {
                animIndex++;
                Image img = list[i].GetChild(0).GetComponent<Image>();
                list[i].GetComponent<Image>().sprite = CommonUtility.GetSprite(emUIAltas.StudyMatrixAtlas, "ljjz-bg02");
                string title = titles[i];
                this.AddTimerEx(animIndex * 0.08f, () =>
                {
                    img.gameObject.SetActive(!isClear);
                    //atlas, title
                    //Debug.Log(atlas + title);
                    img.sprite = ResourceManager.Instance.GetResource(atlas+ title,typeof(Sprite), enResourceType.Prefab).m_content as Sprite;
                    img.SetNativeSize();
                });
            }
            else
                list[i].GetChild(0).gameObject.SetActive(!isClear);
        }
    }
    /// <summary>
    /// 播放标题动画
    /// </summary>
    /// <param name="rowIndex"></param>
    /// <param name="colIndex"></param>
    public void PlayTitleAnim(int rowIndex, int colIndex)
    {
        //rowTitleList  columnTitleList
        rowTitleList[rowIndex].GetChild(0).DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.5f).SetEase(Ease.Linear).OnComplete(()=> {
            rowTitleList[rowIndex].GetChild(0).DOScale(Vector3.one, 0.2f).SetEase(Ease.Linear);
        });

        columnTitleList[colIndex].GetChild(0).DOScale(new Vector3(1.2f, 1.2f, 1.2f), 0.5f).SetEase(Ease.Linear).OnComplete(() => {
            columnTitleList[colIndex].GetChild(0).DOScale(Vector3.one, 0.2f).SetEase(Ease.Linear);
        });
    }
    /// <summary>
    /// 默认显示的矩阵图
    /// </summary>
    /// <param name="_defaultMatrixs"></param>
    /// <param name="index"></param>
    bool IsDefaultMatrixs(int[] _defaultMatrixs, int index)
    {
        bool isDefault = false;
        for (int i = 0; i < _defaultMatrixs.Length; i++)
        {
            if (_defaultMatrixs[i] == index)
            {
                isDefault = true;
                break;
            }
        }
        return isDefault;
    }
    /// <summary>
    /// 当前拖拽数量
    /// </summary>
    int curDragCount = 0;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="index">格子编号(0-8)</param>
    public void AddCount(int index)
    {
        spaceItemList[index].SetItemBg(false,false);
        spaceItemList[index].IsOwnPg = true;
        curDragCount++;        
        if (curDragCount >= dragTotalNum)
        {
            EndGame();
        }
    }

    void EndGame()
    {
        int xunzhangNum = curLevel % ndNum;
        if (xunzhangNum == 0)
            xunzhangNum = ndNum;
        MedalWindow.Instance.ShowXunzhang(xunzhangNum, true, MedalWindow.EXZCountEnum.Five,()=> {
            Debug.Log("结束 ， 开始下一关 ===== ");
            curDragCount = 0;
            curLevel++;
            if (xunzhangNum == ndNum)
            {
                //每五轮结束 弹出击掌  共十五关
               WindowManager.Instance.OpenWindow(WinNames.EnglishLediAnimationPanel);
                EnglishLediAnimationWindow.Instance.PlayLediWinAnimation("study_subtraction/study_subtraced_sound/403050104", "study_phonics/study_phonics_sound/603010706", true, false, () =>
                {
                    EnglishLediAnimationWindow.Instance.HideMask();
                    MedalWindow.Instance.ShowXunzhang(0, false, MedalWindow.EXZCountEnum.Five);
                    if (curLevel > curLelCount)
                    {
                        curLevel = curLelCount;
                        Debug.Log("结束本类型游戏 === ");
                        //TODO 结束本类型游戏
                        OnButtonReturnClick();
                    }
                    else
                    {
                        //直接切换
                        this.AddTimerEx(0.3f, () =>
                        {
                            StartGame(curMatrixType, curLelCount, curLevel);
                        });
                    }
                });
            }
            else
            {
                //直接切换
                this.AddTimerEx(0.3f, () =>
                {
                    StartGame(curMatrixType, curLelCount, curLevel);
                });
            }
        });        
    }

    void OnClear()
    {
        SetTitleItem(null, rowTitleList, true);
        SetTitleItem(null, columnTitleList, true);
        foreach (var item in spaceItemList)
        {
            item.ResetItem();
        }
        foreach (var item in dragItemList)
        {
            item.ResetItem();
            
        }
        //防止最后一个不Destroy掉还会执行OnDrag
        dragItemList.Clear();
    }
     
    protected override void OnOpen(params object[] paramArray)
    {
        //dragCanvasGroup = _DragItems.GetComponent<CanvasGroup>();
        dragTotalNum = colCount * rowCount - randomShowNum;
        WindowManager.Instance.OpenWindow(WinNames.MedalPanel);
        MedalWindow.Instance.ShowXunzhang(0, false, MedalWindow.EXZCountEnum.Six);
    }

 

    protected override void OnClose()
    {
        WindowManager.Instance.CloseWindow(WinNames.EnglishLediAnimationPanel);
        TimerManager.Instance.RemoveAllTimer();
        OnClear();
        titleTrans.gameObject.SetActive(false);
        for (int i = 0; i < spaceItemList.Count; i++)
        {
            spaceItemList[i].SetItemBg(false);
        }
        Debug.Log("  OnClose == ");
    }

    public void OnDestroy()
    {
        /*rowTitleList = null;
        columnTitleList = null;
        spaceItemList = null;
        dragItemList = null;*/
    }

    protected override void OnUpdate()
    {
        
    }

    protected override void OnRefresh()
    {
        base.OnRefresh();
    }

    protected override void AddListeners()
    {
        _Btn_Return.onClick.AddListener(OnButtonReturnClick);
    }

    protected override void RemoveListensers()
    {
        _Btn_Return.onClick.RemoveAllListeners();
    }


    #region uievent

    private void OnButtonReturnClick()
    {
        WindowManager.Instance.OpenWindow(WinNames.MatrixLevelPanel);
        WindowManager.Instance.CloseWindow(WinNames.MatrixInfoPanel,true);
    }

    

    #endregion

 


}
